package cn.yangliu.nacos.management.handler;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import cn.yangliu.nacos.comm.config.security.SecurityProperties;
import cn.yangliu.nacos.comm.config.security.handler.AuthorityHandler;
import cn.yangliu.nacos.comm.model.Oauth2UserModel;
import cn.yangliu.nacos.comm.tools.SecurityUtils;
import cn.yangliu.nacos.management.entity.sys.Authority;
import cn.yangliu.nacos.management.service.sys.AuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * The type of nacos.
 *
 * @author 问道于盲
 * @date 2020 -01-04
 */
@Component
public class ManagementAuthorityHandler implements AuthorityHandler {

    /**
     * current class instance's member.
     * The Authority service.
     */
    @Autowired
    private AuthorityService authorityService;

    /**
     * current class instance's member.
     * The Properties.
     */
    @Autowired
    private SecurityProperties properties;

    /**
     * current class instance's member.
     * The Admins.
     */
    private Set<String> admins;

    /**
     * Init.
     */
    @PostConstruct
    public void init(){
        admins = new HashSet<>(properties.getAdmins());
        admins.add("admin");
    }

    /**
     * Find authorities list.
     *
     * @param authentication the authentication
     * @return the list
     */
    @Override
    public List<String> findAuthorities(Authentication authentication) {
        Oauth2UserModel currentUser = SecurityUtils.getCurrentUser();
        List<Authority> authorities;

        if (admins.contains(currentUser.getUsername())) {
            authorities = authorityService.findAllAuthorities();
        }else {
            authorities = authorityService.findAuthoritiesByOauth2Id(currentUser.getId());
        }

        return authorities.stream().map(Authority::getAuthority).collect(Collectors.toList());
    }
}
